package org.tabcap.workspace;

import java.awt.BorderLayout;
import java.awt.Component;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.border.BevelBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;

import org.tabcap.workspace.document.BaseDocument;
import org.tabcap.workspace.gui.output.TCOutput;
import org.tabcap.workspace.gui.text.console.TCConsole;
import org.tabcap.workspace.gui.text.editor.TCEditor;

public class TCWorkspace extends JPanel
{
	private static final long serialVersionUID = -7601791770495913955L;
	
	private static JPanel pack(Component component, String title)
	{
		JPanel panel = new JPanel();
		panel.setLayout(new BorderLayout());
		if(title == null)
			panel.setBorder(new BevelBorder(BevelBorder.LOWERED));
		else
			panel.setBorder(new CompoundBorder(new TitledBorder(title), 
					new BevelBorder(BevelBorder.LOWERED)));
		panel.add(component, BorderLayout.CENTER);
		return panel;
	}
	
	protected JLabel label;
	public JLabel label() { return label; }
	
	protected TCOutput output;
	public TCOutput output() { return output; }
	
	protected TCEditor editor;
	public TCEditor editor() { return editor; }
	public String getEditorText() { return document.text(); }
	
	protected TCConsole console;
	public TCConsole console() { return console; }
	
	protected BaseDocument document;
	public BaseDocument document() { return document; }

	public TCWorkspace(BaseDocument document)
	{
		super(new BorderLayout());
		
		this.document = document;
		
		output = new TCOutput();
		editor = new TCEditor();
		console = new TCConsole();
		label = new JLabel();
		
		document.useTextPane(editor.textPane());
		document.useLabel(label);
		document.setInitialized(true);
		
		JSplitPane consoleSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true,
				pack(editor, "Editor"), pack(console, "Console"));
		consoleSplitPane.setResizeWeight(0.85);
		
		JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, 
				pack(output, "Output"), consoleSplitPane);
		splitPane.setResizeWeight(0.667);
		add(splitPane, BorderLayout.CENTER);
		
		setBorder(new EmptyBorder(0, 0, 10, 0));

		consoleSplitPane.setDividerLocation(0.75);
		splitPane.setDividerLocation(0.75);
	}
	
	public void compile()
	{
		console.clear();
		if(document.validFile() && !document.isWorthless())
		{
			console.addLine("Compiling...");
			System.out.println(getEditorText());
			console.addLine("Compilation Successful!");
		}
		else
			console.addErrorLine("Nothing to compile!");
	}
	
	public void run()
	{
		console.clear();
		console.addLine("Running...");
	}
}